// Modules to control application life and create native browser window
const {app, BrowserWindow, Menu} = require('electron')
const path = require('path')

const {newTray} = require("./utils/tray");

const {getSystemType,getSystemVersion} = require("./utils/system");
const logger = require('electron-log')
const {loggerInit} = require("./utils/logger");
const {ipcMainOn} = require("./utils/windowActions");
const NODE_ENV = process.env.NODE_ENV
const remoteMain = require('@electron/remote/main');
remoteMain.initialize();

//启用全局变量以防止对象被销毁
global.myWindows= {
    mainWindow: null,
    mainUrl: null,
    appTray: null,
    systemType: null,
    systemVersion: null,
    appPath: null,
    isLogout: false
}
myWindows.systemType = getSystemType()
logger.info('systemType:'+myWindows.systemType)
myWindows.systemVersion = getSystemVersion()
logger.info('systemVersion:'+myWindows.systemVersion)

loggerInit()
logger.info('app.getAppPath():'+app.getAppPath());
let appPath= app.getAppPath().replace(/app\.asar$/,"")
//判断最后没有path.sep的话，就加上
if(appPath.lastIndexOf(path.sep)!==appPath.length-1){
    appPath+=path.sep
}

myWindows.appPath=appPath
logger.info('appPath:'+myWindows.appPath)






let loadUrl =null;
let willQuitApp = false



logger.info('客户端启动中...', 'NODE_ENV:' + NODE_ENV)
logger.info('NODE_ENV:' + NODE_ENV)
//单例模式
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock ) {
    logger.info('桌面客户端已经在运行中,不重复启动。终止本次启动')
    app.quit()
} else {
    app.on('second-instance', (event, commandLine, workingDirectory) => {
        logger.info('second-instance')
        // 当运行第二个实例时,将会聚焦到myWindow这个窗口
        try {
            if (myWindows.mainWindow) {
                if (myWindows.mainWindow.isMinimized()){
                    myWindows.mainWindow.restore()
                }
                myWindows.mainWindow.show();
                myWindows.mainWindow.focus()
            }
        }catch (e){
            logger.error()
            logger.error('second-instance'+e)
        }

    })

    // if(NODE_ENV !== 'development'){
    //     process.on('uncaughtException',(err,origin)=>{
    //         //收集日志
    //         //显示异常提示信息或者重新加载应用
    //         logger.error('uncaughtException:'+err)
    //     })
    // }



    //忽略请求远程服务器上证书错误
    app.commandLine.appendSwitch('--ignore-certificate-errors', 'true')
    // 创建 myWindow, 加载应用的其余部分, etc...
    app.whenReady().then(() => {
        createWindow()
        app.on('activate', () => {
            myWindows.mainWindow.show()
        })
        myWindows.mainWindow.on('close', (event) => {
            logger.info('close========================')
            logger.info('close '+willQuitApp)
            if (willQuitApp) {
                logger.info('myWindows.isLogout:'+myWindows.isLogout)
                if(!myWindows.isLogout){
                    logger.info('close 退出程序,调用退出接口')
                    appQuit()
                    event.preventDefault()
                }else{
                    logger.info('close 退出登录')
                }

            }else{
                event.preventDefault()
                myWindows.mainWindow.hide()

            }
        })
    })

    app.on('window-all-closed', (event) => {
        logger.info('window-all-closed========================')
        if (process.platform !== 'darwin') {
            app.quit()
        }else{
            event.preventDefault()
            myWindows.mainWindow.hide()
        }
    })

    //macos下，点击dock退出调用退出接口
    app.on('before-quit', (event) => {
        logger.info('before-quit')
        willQuitApp = true
        myWindows.mainWindow.hide()
    })



}


//这里的配置手动写的，也可以使用cross-env插件配置

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
/*隐藏electron创听的菜单栏*/
Menu.setApplicationMenu(null)

// app.commandLine.appendSwitch('ignore-gpu-blacklist', 'true');


async function createWindow() {
    logger.info('createWindow========================')
    // Create the browser window.
    myWindows.mainWindow = new BrowserWindow({
        width: 940,
        // minWidth: 940,
        height: 640,
        // minHeight: 640,
        transparent: true,
        icon: __dirname + "/public/logo.png",
        show: true,
        frame: false,
        titleBarStyle: 'hidden',
        resizable: false,
        movable: true,
        useContentSize: true,
        contextIsolation: false, // 禁用上下文隔离
        sandbox: false,           // 确保沙盒模式关闭
        webPreferences: {
            nodeIntegration: true,
            webviewTag: true, //开启webview
            contextIsolation: false,
            enableRemoteModule: true,//允许使用electron的remote模块
            webSecurity: false,
            preload: path.join(__dirname, 'preload.js'),
            // contentSecurityPolicy: "default-src 'self'; script-src 'self' 'unsafe-inline'"
        },
    })

    remoteMain.enable(myWindows.mainWindow); // 启用远程支持


    //如下代码优化
    if (NODE_ENV === 'development') {
        myWindows.mainWindow.webContents.openDevTools()
        loadUrl = 'http://localhost:25000'
    } else {
        loadUrl = `file://${path.join(__dirname, '../dist/index.html')}`
    }
    logger.info('loadUrl:' + loadUrl)
    myWindows.mainUrl = loadUrl
    myWindows.mainWindow.loadURL(loadUrl)

    //页面内容保护，不被捕获
    // myWindows.mainWindow.setContentProtection(true);


    newTray()
    ipcMainOn()

}



